package com.scaffold.springbootscaffold.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Map;

@Slf4j
@Controller
@ConditionalOnProperty(prefix = "websocket", name = "enabled", havingValue = "true")
public class WebSocketHandler {

    @Resource
    private SimpMessagingTemplate messagingTemplate;

    @Resource
    private WebSocketSessionManager sessionManager;

    /**
     * 广播消息
     */
    @MessageMapping("/broadcast")
    @SendTo("/topic/broadcast")
    public WebSocketMessage broadcast(WebSocketMessage message) {
        log.info("收到广播消息：{}", message);
        message.setTimestamp(Instant.now().toEpochMilli());
        return message;
    }

    /**
     * 点对点消息
     */
    public void sendToUser(String userId, String content) {
        if (!sessionManager.isOnline(userId)) {
            log.warn("用户{}不在线", userId);
            return;
        }

        String destination = "/queue/message/" + userId;
        WebSocketMessage message = new WebSocketMessage();
        message.setTo(userId);
        message.setContent(content);
        message.setTimestamp(Instant.now().toEpochMilli());
        messagingTemplate.convertAndSend(destination, message);
        log.info("发送消息到{}：{}", destination, message);
    }

    // 获取在线用户列表
    public Map<String, String> getOnlineUsers() {
        return sessionManager.getOnlineUsers();
    }
} 